1. Break Statement
The break statement is used to terminate the nearest enclosing loop or a switch statement immediately. When a break statement is executed, the control exits from the loop or switch, skipping any remaining iterations or cases.
Syntax:
break;
Usage in Loops:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop when i equals 3
}
printf("%d ", i);
}
return 0;
}
Output:
1 2
Usage in Switch:
#include < stdio.h>
int main() {
int choice = 2;
switch (choice) {
case 1:
printf("Option 1\n");
break;
case 2:
printf("Option 2\n");
break; // Exits the switch after this case
default:
printf("Default Option\n");
}
return 0;
}
Output:
Option 2
2.Continue Statement
The continue statement is used to skip the current iteration of the nearest enclosing loop and move to the next iteration. Unlike break, continue does not terminate the loop entirely; it just skips the remaining code in the current iteration.
Sntax:
continue;
Usage:
#include < stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the rest of the loop body when i equals 3
}
printf("%d ", i);
}
return 0;
}
Output:
1 2 4 5
Key Differences Between Break and Continue:
| Aspect | Break | Continue |
|---|---|---|
| Behavior | Terminates the loop entirely. | Skips the current iteration. |
| Effect on Loops | Stops further iterations. | Proceeds with the next iteration. |
| Scope | Works in loops and switch. | Works only in loops. |